<?php

/**
 * System log
 */
class Euso_Model_Log
{
	// TODO: listener
	//TODO: referer


	// Don't throw exception here
	public static function push($module = NULL, $event = NULL,
		$desc = NULL, $params = NULL, $objects = NULL)
	{
		$table = Euso_Model_DbTable_LogEntry::getInstance();

		$sessAcc = Account_Model_Session::getAccount();
		if ($sessAcc != NULL) {
			$accountId = $sessAcc->getId();
		} else {
			$accountId = NULL;
		}

        $dbData = array(
			//TODO: use higher precision timing
			'time' => time() - date('Z'),
			'ipaddress' => $_SERVER['REMOTE_ADDR'],
			'account_id' => $accountId,
			'module' => $module,
		//	'section' => $section,
			'event' => $event,
			'description' => $desc,
        );

		$insertId = $table->insert($dbData);
		if ($insertId < 1) {
			return;
		}

		$logId = $table->getAdapter()->lastInsertId();
		if ($logId < 1) {
			return;
		}

		if (is_array($objects) && count ($objects) > 0) {
			$objectDbTable = Euso_Model_DbTable_LogObject::getInstance();
			foreach ($objects as $o) {
				if (($o instanceof Euso_ObjectRef) === FALSE && is_array($o) === FALSE) {
					continue;
				}
				if (is_array($o)) {
					$dbData = array(
						'log_id' => $logId,
						'object_class' => $o['class'],
						'object_id' => $o['id'],
					);
				} else {
					$dbData = array(
						'log_id' => $logId,
						'object_class' => $o->getObjectClassIdName(),
						'object_id' => $o->getObjectId(),
					);
				}
				$insertId = $objectDbTable->insert($dbData);
			}
		}

		if (is_array($params) && count ($params) > 0) {
			$paramDbTable = Euso_Model_DbTable_LogParam::getInstance();
			foreach ($params as $key => $value) {
				$dbData = array(
					'log_id' => $logId,
					'param_key' => $key,
					'param_value' => $value,
				);
				$paramDbTable->insert($dbData);
			}
		}
	}
}
